package com.example.demo.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.NewEntity;
import com.example.demo.mapper.NewMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author bueryouth
 */
@RestController
@RequestMapping("/news")
public class NewController {
    @Resource
    NewMapper newMapper;

    /**
     * 新增接口
     */
    @PostMapping
    public Result<?> save(@RequestBody NewEntity newEntity) {
        // 判断是否填写时间
        if (newEntity.getTime() == null) {
            newEntity.setTime(new Date());
        }
        newMapper.insert(newEntity);
        return Result.success();
    }

    /**
     * 更新接口
     */
    @PutMapping
    public Result<?> update(@RequestBody NewEntity newEntity) {
        // 判断是否填写时间
        if (newEntity.getTime() == null) {
            newEntity.setTime(new Date());
        }
        newMapper.updateById(newEntity);
        return Result.success();
    }

    /**
     * 删除接口
     */
    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        newMapper.deleteById(id);
        return Result.success();
    }

    /**
     * 查询接口
     */
    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum, // 设置接口默认查询内容
        @RequestParam(defaultValue = "10") Integer pageSize, @RequestParam(defaultValue = "") String search) {
        LambdaQueryWrapper<NewEntity> wrapper = Wrappers.lambdaQuery();
        // 查询字段为空情况
        if (StrUtil.isNotEmpty(search)) {
            wrapper.like(NewEntity::getTitle, search);
        }
        Page<NewEntity> userPage = newMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return Result.success(userPage);
    }
}
